﻿using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;

namespace Jayden.Dll.Core.Drawing
{
	public class ImageHelper
	{
		public static Bitmap Greyscale(Bitmap source)
		{
			Bitmap bitmap = new Bitmap(source.Width, source.Height);
			using (Graphics graphics = Graphics.FromImage(source))
			{
				for (int x = 0; x < source.Width; x++)
				{
					for (int y = 0; y < source.Height; y++)
					{
						Color pixelColor = source.GetPixel(x, y);
						int pixelValue = (int)(pixelColor.R) + (int)(pixelColor.G) + (int)(pixelColor.B);
						pixelValue = pixelValue / 3;
						Color newColor = Color.FromArgb(pixelValue, pixelValue, pixelValue);
						bitmap.SetPixel(x, y, newColor); // Now greyscale
					}
				}
			}
			return bitmap;
		}
		public static Bitmap Resize(Image source, int maxWidth, int maxHeight)
		{
			double ratio = 1.0;
			double heightRatio = source.Height / (double)maxHeight;
			double widthRatio = source.Width / (double)maxWidth;

			if (heightRatio < widthRatio)
				ratio = widthRatio;
			else
				ratio = heightRatio;

			int newWidth = (int)(source.Width / ratio);
			int newHeight = (int)(source.Height / ratio);

			Bitmap bitmap = new Bitmap(newWidth, newHeight);
			using (Graphics graphics = Graphics.FromImage(bitmap))
			{
				graphics.CompositingQuality = CompositingQuality.HighSpeed;
				graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
				graphics.CompositingMode = CompositingMode.SourceCopy;
				graphics.DrawImage(source, 0, 0, newWidth, newHeight);
			}
			return bitmap;
		}
		public static Bitmap GetString(string text, Font font, Brush color, Color backgroundColor)
		{
			SizeF measure;
			using (Bitmap tmp = new Bitmap(1, 1))
			{
				Graphics graphics = Graphics.FromImage(tmp);
				measure = graphics.MeasureString(text, font);
			}
			int width = (int)measure.Width;
			int height = (int)measure.Height;

			if (measure.Width > width)
				width++;
			if (measure.Height > height)
				height++;

			Bitmap bitmap = new Bitmap(width, height);
			using (Graphics g = Graphics.FromImage(bitmap))
			{
				g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
				g.Clear(backgroundColor);
				g.DrawString(text, font, color, 0, 0);
			}
			return bitmap;
		}
	}
}
